package com.fc.app.fcapp.tools;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Build;
import android.os.Looper;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.facebook.common.util.Hex;
import com.fc.app.fcapp.FCApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Created by Administrator on 2018/3/8.
 */

public class Android {
   private static final String TAG = "Android";
    /**
     * 概述：得到当前的屏幕尺寸<br/>
     *
     * @param context
     * @return Display
     * @date 2013-10-22
     */
    public static Display getCurrentDisplay(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        return display;
    }

    /**
     * 概述：得到当前density<br/>
     *
     * @param context
     * @return float
     * @date 2013-12-20
     */
    public static float getDisplayDensity(Context context) {
        dm = context.getResources().getDisplayMetrics();
        float density = dm.density;
        return density;
    }

    /**
     * 概述：得到屏幕的宽度<br/>
     *
     * @param context
     * @return int
     * @date 2013-10-22
     */
    public static int getDisplayWidth(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        if (display == null) {
            return 1920;
        }
        return display.getWidth();
    }

    /**
     * 概述：得到屏幕的高度<br/>
     *
     * @param context
     * @return int
     * @date 2013-10-22
     */
    public static int getDisplayHeight(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        return display.getHeight();
    }


    private static DisplayMetrics dm = null;

    private synchronized static DisplayMetrics getDisplayMetrics() {
        if (dm == null) {
            dm = new DisplayMetrics();
        }
        dm.setToDefaults();
        return dm;
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2dip(float pxValue) {
        DisplayMetrics dm = getDisplayMetrics();
        return (int) (pxValue / dm.density + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @return
     */
    public static int dip2px(float dipValue) {
        DisplayMetrics dm = getDisplayMetrics();
        return (int) (dipValue * dm.density + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(float pxValue) {
        DisplayMetrics dm = getDisplayMetrics();
        return (int) (pxValue / dm.scaledDensity + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(float spValue) {
        DisplayMetrics dm = getDisplayMetrics();
        return (int) (spValue * dm.scaledDensity + 0.5f);
    }

    public static Object getMetaData(Context context, String packageName, String key) {
        ApplicationInfo applicationInfo = null;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_META_DATA);
            if (applicationInfo != null) {
                Object value = null;
                if (applicationInfo.metaData != null) {
                    value = applicationInfo.metaData.get(key);
                }
                if (value == null) {
                    return null;
                }
                return value;
            }
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static List<ComponentName> getComponentNames(Context context, String action) {
        List<ComponentName> ret = new ArrayList<ComponentName>();
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(action);
        List<ResolveInfo> list = pm.queryBroadcastReceivers(intent, 0);
        for (ResolveInfo i : list) {
            ret.add(new ComponentName(i.activityInfo.packageName, i.activityInfo.name));
        }

        list = pm.queryBroadcastReceivers(intent, PackageManager.GET_DISABLED_COMPONENTS);
        for (ResolveInfo i : list) {
            ret.add(new ComponentName(i.activityInfo.packageName, i.activityInfo.name));
        }
        Collections.sort(ret, new Comparator<ComponentName>() {
            public int compare(ComponentName arg0, ComponentName arg1) {

                return arg0.getPackageName().compareTo(arg1.getPackageName());
            }
        });
        return ret;
    }

    public static List<ComponentName> getCOMPLETEDComponentNamesByPkg(Context context, String pkg) {
        List<ComponentName> ret = new ArrayList<ComponentName>();
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
        intent.setPackage(pkg);
        List<ResolveInfo> list = pm.queryBroadcastReceivers(intent, PackageManager.GET_DISABLED_COMPONENTS);
        if (list != null && list.size() > 0) {
            for (ResolveInfo i : list) {
                Log.d("completed", "getCOMPLETEDComponentNamesByPkg    pkg:" + i.activityInfo.packageName + " activity:" + i.activityInfo.name);
                ret.add(new ComponentName(i.activityInfo.packageName, i.activityInfo.name));
            }
        }
        return ret;
    }

    public static void setComponentEnabledSetting(Context context, ComponentName comptName,
                                                  int state) {
        try {
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(comptName, state, PackageManager.DONT_KILL_APP);//PackageManager.DONT_KILL_APP);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param context
     * @param comptName
     * @return  0:COMPONENT_ENABLED_STATE_DEFAULT 1:COMPONENT_ENABLED_STATE_ENABLED  2:COMPONENT_ENABLED_STATE_DISABLED
     */
    public static int getComponentEnabledSetting(Context context, ComponentName comptName) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getComponentEnabledSetting(comptName);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean isPackageDisabled(Context context, String packageName) {
        List<ComponentName> list = getInstalledAppComponentNames(context, packageName);
        for (ComponentName cn : list) {
            if (getComponentEnabledSetting(context, cn) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                return false;
            }
        }
        return true;
    }

    public static List<ComponentName> getInstalledAppComponentNames(Context context, String pkgName) {
        List<ComponentName> ret = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        try {
            ApplicationInfo appInfo = pm.getApplicationInfo(pkgName, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES | PackageManager.GET_RECEIVERS | PackageManager.GET_PROVIDERS);
            Intent intent = new Intent();
            intent.setPackage(appInfo.packageName);
            Log.d("aaa", "[package]" + appInfo.packageName);
            List<ResolveInfo> list = pm.queryIntentServices(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                Log.d("aaa", "  [service]" + i.serviceInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.serviceInfo.name));
            }
            list = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                Log.d("aaa", "  [activity]" + i.activityInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.activityInfo.name));
            }
            list = pm.queryBroadcastReceivers(intent, PackageManager.GET_DISABLED_COMPONENTS);
            for (ResolveInfo i : list) {
                Log.d("aaa", "  [receiver]" + i.activityInfo.name);
                ret.add(new ComponentName(appInfo.packageName, i.activityInfo.name));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static int getVersionCode(Context context, String pkg) {
        PackageManager mPackageManager = context.getPackageManager();
        try {
            return mPackageManager.getPackageInfo(pkg, 0).versionCode;
        } catch (Exception e) {
            return -1;
        }
    }

    public static String getVersionName(Context context, String pkg) {
        Log.d("TEST", "getVersionName context:" + context + "  pkg:" + pkg);
        PackageManager mPackageManager = context.getPackageManager();
        try {
            return mPackageManager.getPackageInfo(pkg, 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getAppName(Context context, String pkg) {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(pkg, 0);
            return pm.getApplicationLabel(applicationInfo).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean checkIsTopActivity(String... packageNames) {
        try {
            ActivityManager am = (ActivityManager) FCApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            String pkg = cn.getPackageName();
            Log.d(TAG,"checkIsTopActivity current running top activity is from package:" + pkg);
            for (String packageName : packageNames) {
                if (pkg.equals(packageName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static Drawable getAppIcon(Context context, String pkg) {
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(pkg, 0);
            return pm.getApplicationIcon(pkg);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getActivityName(Context context, ComponentName cn) {
        try {
            PackageManager pm = context.getPackageManager();
            ActivityInfo ai = pm.getActivityInfo(cn, 0);
            return ai.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Drawable getActivityIcon(Context context, ComponentName cn) {
        try {
            PackageManager pm = context.getPackageManager();
            ActivityInfo ai = pm.getActivityInfo(cn, 0);
            return ai.loadIcon(pm);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static ComponentName getLauncherActivity(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(packageName);
        List<ResolveInfo> resolveInfo = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS);
        if (resolveInfo != null && resolveInfo.size() > 0) {
            ResolveInfo info = resolveInfo.get(0);
            return new ComponentName(packageName, info.activityInfo.name);
        }
        return null;
    }

//    public static boolean isPackageInstalled(Context context, String pkg) {
//        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
//        PackageInfo intent;
//        try {
//            intent = mPackageManager.getPackageInfo(pkg, 0);
//        } catch (NameNotFoundException e) {
////            e.printStackTrace();
//            return false;
//        }
//        if (intent == null)
//            return false;
//        else
//            return true;
//    }

    public static boolean isNetConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable() && info.isConnected()) {
            return true;
        } else {
            return false;
        }
    }



    public static String throwable2String(Throwable t) {
        String format = "    at %s.%s(%s:%d)\n";
        String msg = t.toString() + "\n";
        StackTraceElement[] es = t.getStackTrace();
        for (StackTraceElement e : es) {
            msg += String.format(format, e.getClassName(), e.getMethodName(), e.getFileName(),
                    e.getLineNumber());
        }
        return msg;
    }

    public static double getBootUptime() {
        String ret = "";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
                    "/proc/uptime")));
            String line = reader.readLine();
            String[] results = line.split("\\s+");
            for (int i = 0; i < results.length; i++) {
                if (!results[i].equals("")) {
                    ret = results[i];
                    break;
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        double uptime = 0d;
        try {
            uptime = Double.parseDouble(ret);
        } catch (Exception e) {
            uptime = 0d;
            e.printStackTrace();
        }
        return uptime;
    }

    public static Uri getResourceURI(Context context, int resID) {
        String uri = new StringBuilder("res://").append(context.getPackageName()).append("/").append(resID).toString();
        return Uri.parse(uri);
    }

    public static Uri getAndroidResUri(Context context, int resID) {
        String uri = new StringBuilder("android.resource://").append(context.getPackageName()).append("/").append(resID).toString();
        return Uri.parse(uri);
    }

    public static String getFrescoResourceUrl(Context context, int resId) {
        return new StringBuilder("res://").append(context.getPackageName()).append("/").append(resId).toString().toString();
    }

    public static boolean isRunOnMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    private static String processName = null;

    public static synchronized String getMyProcessName(Context c) {
        if (processName != null) {
            return processName;
        }
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                processName = appProcess.processName;
                return processName;
            }
        }
        return "";
    }

    public static ComponentName startService(Context c, String pkgName, String action) {
        try {
            Intent i = new Intent(action);
            i.setPackage(pkgName);
            return c.startService(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean stopService(Context c, String pkgName, String action) {
        try {
            Intent i = new Intent(action);
            i.setPackage(pkgName);
            return c.stopService(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static boolean isAppRunningAtFront(Context c, String pkgname) {
        try {
            ActivityManager am = (ActivityManager) c.getSystemService(Activity.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            return componentInfo.getPackageName().equals(pkgname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isInstalledOnSDCard(Context c, String pkg) {
        PackageManager pm = c.getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(pkg, PackageManager.GET_DISABLED_COMPONENTS);
//            Log.d("install", " isInstalledOnSDCard:" + info.packageName);
            if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static String getAppNameByPkg(Context context, String pkg) {
        String name = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(pkg, 0);
            name = (String) packageManager.getApplicationLabel(applicationInfo);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return name;
    }

    public static String getNameByActivity(Context context, String packageName, String activityName) {
        try {
            PackageManager pm = context.getPackageManager();
            ActivityInfo ai = pm.getActivityInfo(new ComponentName(packageName,
                    activityName), 0);
            return ai.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return getAppNameByPkg(context, packageName);
        }
    }

    public static String readAssetFile(Context context, String assetFile) {
        String ret = "";
        AssetManager assetManager = context.getAssets();
        try {
            InputStream is = assetManager.open(assetFile, AssetManager.ACCESS_BUFFER);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                ret += line;
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }


    public static final int INSTALL_LOCATION_UNSPECIFIED = -1;
    public static final int INSTALL_LOCATION_AUTO = 0;
    public static final int INSTALL_LOCATION_INTERNAL_ONLY = 1;
    public static final int INSTALL_LOCATION_PREFER_EXTERNAL = 2;

    private static int getConfigInstallLocation() {
        int ret = Settings.Secure.getInt(FCApplication.getContext().getContentResolver(), "default_install_location", 0);
        Log.d("install", "settings getInstallLocation:" + ret);
//        if(ret == 0)
//            return 2;    //应酷开系统需求，如果location为自动（0），则当成外部（2）来处理。
        return ret;
        // 0：自动
        // 1：内部
        // 2：外部
    }

    public static int getInstallLocation(String apk) {
        int pos = getConfigInstallLocation();
        Log.d("install", apk + "settings getInstallLocation:" + pos);
        return pos;
    }

    public static boolean isInstalledInSystemPartition(String pkg) {
        PackageManager pm = FCApplication.getContext().getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(pkg, PackageManager.GET_DISABLED_COMPONENTS);
            Log.d("install", " sourceDir:" + info.sourceDir);
            if (info.sourceDir.startsWith("/system") || info.sourceDir.startsWith("system")) {
                return true;
            }
            return false;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isPkgSystemSign(String pkg) {
        PackageManager pm = FCApplication.getContext().getPackageManager();
        try {
//            PackageInfo info = pm.getPackageInfo(pkg, 0);
//            String sharedUserId = info.sharedUserId;
            int sign = pm.checkSignatures(FCApplication.getContext().getPackageName(), pkg);
            if (sign >= 0)     //签名匹配
            {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean needInstallSystem(String apkPath) {
        PackageInfo pkgInfo = FCApplication.getContext().getPackageManager().getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        Log.d("install", "(pkgInfo != null):" + (pkgInfo != null));
        if (pkgInfo != null) {
            if (pkgInfo.sharedUserId != null && pkgInfo.sharedUserId.equals("android.uid.system")) {
                Log.d("install", apkPath + "is system uid !");
                return true;
            }
            return isInstalledInSystemPartition(pkgInfo.packageName);
        }
        return false;
    }


    public static Object invokeReflectMethod(Object obj, String methodName, Object... params) {
        try {
            if (params != null) {
                Class<?>[] clazzez = new Class<?>[params.length];
                for (int i = 0; i < params.length; i++) {
                    clazzez[i] = params[i].getClass();
                }

                Method method = obj.getClass().getMethod(methodName, clazzez);
                return method.invoke(obj, params);
            } else {
                Method method = obj.getClass().getMethod(methodName);
                return method.invoke(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getStaticFieldValue(Class clazz, String fieldName) {
        try {
            Field field = clazz.getField(fieldName);
            if (field != null) {
                field.setAccessible(true);
                return field.get(clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getFieldValue(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getField(fieldName);
            if (field != null) {
                field.setAccessible(true);
                return field.get(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static List<String> getInstalledPackages(Context c) {
        PackageManager pm = c.getPackageManager();
        List<PackageInfo> list = pm.getInstalledPackages(0);
        List<String> packages = new ArrayList<>();
        for (PackageInfo pi : list) {
            packages.add(pi.packageName);
        }
        return packages;
    }

    public static String getTopPackageName(Context context) {
        String pkgName = null;
        ActivityManager manager = ((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE));

        try {
            if (Build.VERSION.SDK_INT >= 21) {
                List<ActivityManager.RunningAppProcessInfo> pis = manager.getRunningAppProcesses();
                ActivityManager.RunningAppProcessInfo topAppProcess = pis.get(0);
                if (topAppProcess != null && topAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    if(topAppProcess.pkgList != null && topAppProcess.pkgList.length > 0) {
                        return topAppProcess.pkgList[0];
                    } else {
                        pkgName = topAppProcess.processName;
                    }
                }
            } else {
                //getRunningTasks() is deprecated since API Level 21 (Android 5.0)
                List localList = manager.getRunningTasks(1);
                ActivityManager.RunningTaskInfo localRunningTaskInfo = (ActivityManager.RunningTaskInfo)localList.get(0);
                pkgName = localRunningTaskInfo.topActivity.getPackageName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pkgName;
    }

    public static ComponentName getRunningTopActivity() {
        try {
            ActivityManager am = (ActivityManager) FCApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
            return am.getRunningTasks(1).get(0).topActivity;
        } catch (Exception e) {
        }
        return null;
    }

    public static String getRunningProcessName(Context c) {
        String pidName = "";
        try {
            ComponentName cn = getRunningTopActivity();
            PackageManager pm = c.getPackageManager();
            pidName = pm.getActivityInfo(cn, 0).processName;
        } catch (Exception e) {

        }
        return pidName;
    }

    public static boolean isZh(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAppSaferOpen(Context c) {
        return true;
        //20160726 系统安全防护已不让修改，永远为阻止状态，但应用圈不受影响，所以永远允许安装
//        int tag = Settings.Secure.getInt(c.getContentResolver(),
//                Settings.Secure.INSTALL_NON_MARKET_APPS, 0);
//        Log.d("safe", "isAppSaferOpen:" + tag);
//        return tag > 0;
    }

    public static String getCurrentProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }

    public static boolean isProcessExist(Context context,String processName){
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            Log.d("test","process:"+appProcess.processName);
            if (appProcess.processName.equals(processName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isPackageInstalled(Context context, String pkg) {
        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
        PackageInfo intent;
        try {
            intent = mPackageManager.getPackageInfo(pkg, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
        if (intent == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测 响应某个意图的Activity 是否存在
     * http://blog.csdn.net/top_code/article/details/17285695
     *
     * @param context
     * @param intent
     * @return
     */
    public static boolean isIntentAvailable(Context context, Intent intent) {
        if (intent == null) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES
                        | PackageManager.GET_RECEIVERS
                        | PackageManager.GET_SERVICES
                        | PackageManager.GET_PROVIDERS);
        return list.size() > 0;
    }
}

